<template>
  <el-row type="flex" style="margin-top: 1rem; margin-bottom: 1rem;">
    <el-col :span="24">
      <div class="add-pro-box-title t-a-l">基础信息</div>
      <div class="add-pro-box-info">
        <el-form
          :model="saveData"
          :rules="saveRule"
          ref="saveData"
          label-position="right"
          label-width="25%"
          :validate-on-rule-change="true"
        >
          <el-row class="formRequired">
            <el-col :span="12">
              <el-form-item
                label="商品名称："
                prop="appInfo.name"
                class="t-a-l is-required m-t-20"
                :error="checkNameError"
              >
                <el-input
                  class="add-moc-input"
                  v-model.trim="saveData.appInfo.name"
                  placeholder="请输入商品名称"
                  maxlength="30"
                  style="width: 217px;"
                  auto-complete="false"
                ></el-input>
                <!--@input="checkName"-->
              </el-form-item>
              <el-form-item label="产品类型：" prop="appInfo.typeId" class="t-a-l is-required m-t-20">
                <el-select
                  class="add-moc-input"
                  v-model="saveData.appInfo.typeId"
                  placeholder="请选择产品类型"
                >
                  <el-option
                    v-for="item in searchFilter.typeIdArr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="产品分类：" prop="appInfo.cateId" class="t-a-l is-required m-t-20">
                <el-select
                  class="add-moc-input"
                  v-model="saveData.appInfo.cateId"
                  placeholder="请选择产品分类"
                >
                  <el-option
                    v-for="item in searchFilter.cateIdArr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="厂商：" prop="appInfo.acpId" class="t-a-l is-required m-t-20">
                <el-select
                  class="add-moc-input"
                  v-model="saveData.appInfo.acpId"
                  placeholder="请选择厂商"
                  @change="acpChange"
                >
                  <el-option
                    v-for="item in searchFilter.acpIdArr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item
                label="到账方式："
                prop="appInfo.rechargeMode"
                class="t-a-l is-required m-t-20"
                style="padding-top:10px"
              >
                <el-radio-group v-model="saveData.appInfo.rechargeMode">
                  <el-radio :label="0">直充</el-radio>
                  <el-radio :label="1">卡密</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="商品编号："
                prop="code"
                class="t-a-l m-t-20"
                v-if="saveData.appInfo.code !== ''"
              >
                <span v-html="saveData.appInfo.code"></span>
              </el-form-item>

              <el-form-item label="商品图标：" prop="appInfo.icon" class="t-a-l is-required m-t-20">
                <img
                  class="f-l upload-img"
                  :src="saveData.appInfo.icon? ftpUrl+saveData.appInfo.icon :''"
                  :onerror="baseUploadImg"
                >
                <el-upload
                  ref="preIcon"
                  class="add-moc-upload"
                  name="file"
                  action="none"
                  :before-upload="beforeUpload"
                  :on-change="changeUpload"
                  :show-file-list="false"
                  accept="image/png,image/jpeg"
                  drag
                  :multiple="false"
                >
                  <div class="el-upload__text">点击或拖拽到此区域上传</div>
                </el-upload>
              </el-form-item>

              <el-form-item label="是否推荐：" prop="appInfo.isReco" class="t-a-l is-required m-t-20">
                <el-switch
                  v-model="saveData.appInfo.isReco"
                  :active-value="1"
                  :inactive-value="0"
                  active-text="推荐"
                  inactive-text="不推荐"
                ></el-switch>
              </el-form-item>

              <el-form-item
                label="账号类型："
                prop="appInfo.acctId"
                class="t-a-l m-t-20"
                v-if="saveData.appInfo.rechargeMode == 0"
              >
                <el-select
                  class="add-moc-input"
                  v-model="saveData.appInfo.acctId"
                  placeholder="请选择账号类型"
                >
                  <el-option
                    v-for="item in searchFilter.acctIdArr"
                    :key="item.id"
                    :label="item.mainName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="区服配置："
                prop="gameId"
                class="t-a-l m-t-20"
                v-if="saveData.appInfo.rechargeMode == 0"
              >
                <el-select
                  class="add-moc-input"
                  v-model="saveData.appInfo.gameId"
                  placeholder="请选择游戏区服"
                  clearable
                >
                  <el-option
                    v-for="item in searchFilter.gameIdArr"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
                <!-- <i class="el-icon-edit" @click="handlerAddGame"></i> -->
              </el-form-item>
              <el-form-item label="关键词：" prop="label" class="t-a-l m-t-20">
                <el-input
                  class="add-moc-input"
                  v-model.trim="saveData.appInfo.label"
                  placeholder="请输入关键词"
                  maxlength="30"
                  style="width: 217px;"
                  auto-complete="false"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 充值类型 -->
          <el-row type="flex">
            <el-col>
              <el-form-item label-width="12.5%" label="充值类型：" class="t-a-l is-required m-t-20">
                <el-row type="flex" class="saveData_recharge_type border-bottom">
                  <el-col :span="3">
                    <el-form-item label-width="90%" label="充值类型" prop="name" class="is-required"></el-form-item>
                  </el-col>
                  <el-col :span="3">
                    <el-form-item label-width="90%" label="单位" prop="unit" class="is-required"></el-form-item>
                  </el-col>
                  <el-col :span="3">
                    <el-form-item
                      label-width="90%"
                      label="最大充值数量"
                      prop="maxmum"
                      class="is-required"
                    ></el-form-item>
                  </el-col>
                  <el-col :span="3">
                    <el-form-item
                      label-width="90%"
                      label="最小充值数量"
                      prop="minmum"
                      class="is-required"
                    ></el-form-item>
                  </el-col>
                  <el-col :span="3">
                    <el-form-item
                      label-width="90%"
                      label="输入数量倍数"
                      prop="multiple"
                      class="is-required"
                    ></el-form-item>
                  </el-col>
                  <el-col :span="3">
                    <el-form-item
                      label-width="90%"
                      label="1元兑换比例"
                      prop="subscriptionRatio"
                    ></el-form-item>
                    <!--class="is-required"-->
                  </el-col>
                </el-row>

                <el-row
                  type="flex"
                  class="saveData_recharge_type m-t-20"
                  v-for="(item, index) in saveData.appPriceTypeList"
                  :key="item.id"
                >
                  <el-col :span="3">
                    <el-form-item :prop="`appPriceTypeList.${index}.name`" :rules="saveRule2.name">
                      <el-input style="width:90%" v-model="item.name"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="3">
                    <el-form-item :prop="`appPriceTypeList.${index}.unit`" :rules="saveRule2.unit">
                      <el-input style="width:90%" v-model="item.unit"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="3">
                    <el-form-item
                      :prop="`appPriceTypeList.${index}.maxmum`"
                      :rules="saveRule2.maxmum"
                    >
                      <el-input style="width:90%" v-model.number="item.maxmum"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="3">
                    <el-form-item
                      :prop="`appPriceTypeList.${index}.minmum`"
                      :rules="saveRule2.minmum"
                    >
                      <el-input style="width:90%" v-model.number="item.minmum"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="3">
                    <el-form-item
                      :prop="`appPriceTypeList.${index}.multiple`"
                      :rules="saveRule2.multiple"
                    >
                      <el-input
                        style="width:90%"
                        v-model.number="item.multiple"
                        onkeypress="return event.keyCode>=48&&event.keyCode<=57"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="3">
                    <el-form-item
                      :prop="`appPriceTypeList.${index}.subscriptionRatio`"
                      :rules="saveRule2.subscriptionRatio"
                    >
                      <el-input style="width:90%" v-model.number="item.subscriptionRatio"></el-input>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="3">
                    <el-form-item
                      :prop="`appPriceTypeList.${index}.subscriptionRatio`"
                      :rules="saveRule2.subscriptionRatio"
                    >
                      <el-input
                      style="width:90%" v-model.number="item.subscriptionRatio"></el-input>
                    </el-form-item>
                  </el-col>-->
                  <i class="el-icon-plus" v-if="index == 0" @click="addDomain"></i>
                  <i class="el-icon-minus" v-if="index != 0" @click="delDomain(item,index)"></i>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex">
            <el-col :span="24">
              <el-form-item label-width="12.5%" label="商品详情：" class="uploadBox t-a-l m-t-20">
                <!--<el-button class="font-c border-c" size="small">编辑</el-button>-->
                <!--<el-input v-model="saveData.appPage.content"></el-input>-->

                <el-row type="flex">
                  <el-upload
                    ref="preIcon"
                    class="add-content-upload"
                    action="none"
                    :before-upload="beforeUploadContent"
                    :on-change="changeUploadContent"
                    :on-remove="handleRemove"
                    :multiple="false"
                    :file-list="fileList"
                    accept="image/png,image/jpeg"
                    drag
                    list-type="picture"
                  >
                    <div class="el-upload__text">添加商品详情</div>
                  </el-upload>
                </el-row>

                <!--<el-row type="flex">
                  <el-col :span="12" v-for="(item, index) in saveData.fileInfoList" :key="index" v-if="item.type == 6">
                    <img
                      class="f-l upload-content-img m-t-20"
                      :src="item.fileUrl?ftpUrl+item.fileUrl:''"
                      :onerror="baseUploadImg"
                    >
                  </el-col>
                </el-row>-->
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex">
            <el-col style="text-align: center">
              <!--<el-button class="font-c border-c" size="small" @click="preview()">预览</el-button>-->
              <el-button class="font-c border-c" size="small" @click="save(1)">保存并继续添加</el-button>
              <el-button class="font-c border-c" size="small" @click="save(2)">保存</el-button>
              <el-button class="font-c border-c" size="small" @click="closeForm()">取消</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-col>
  </el-row>
</template>
<script>
export default {
  name: "detail",
  data() {
    const validateImage = (rule, value, callback) => {
      callback();
    };
    const validateNumber = (rule, value, callback) => {
      let reg = new RegExp(
        "^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$"
      );
      let result = reg.test(value);
      if (!result) {
        callback(new Error("必须为大于0的数字"));
      } else {
        callback();
      }
    };
    //充值类型、单位不能有空格
    const validateUnit= (rule,value,callback) =>{
      const reg =/^[^\s]*$/;
      let result = reg.test(value);
      if (!result) {
        callback(new Error("不能输入空格"));
      } else {
        callback();
      }
    };
    //校验最大值是否比最小值小
    const validateMaxnum = (rule,value,callback,a)=>{
      let reg = new RegExp(
        "^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$"
      );
      let result = reg.test(value);
      let index;
      for(let key in a){
        index = key;
      }
      index = index.split('.')[1];
      let minmun = this.saveData.appPriceTypeList[index].minmum;
      let multiple = this.saveData.appPriceTypeList[index].multiple;
      if (!result) {
        callback(new Error("必须为大于0的数字"));
      }else if(value > 999999){
        callback(new Error("最大数量限制6位数"));
      }else if(value < minmun){
        callback(new Error("最大数量不能小于最小数量"));
      }else if(!multiple){
        //此时倍数还没填
        callback();
      }else if(value % multiple !== 0){
        callback(new Error("最大数量必须整除数量倍数"));
      } else {
        callback();
      }

    };
    //校验最小值
    const validateMinnum = (rule,value,callback,a)=>{
      let reg = new RegExp(
        "^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$"
      );
      let result = reg.test(value);
      let index;
      for(let key in a){
        index = key;
      }
      index = index.split('.')[1];
      let maxmum = this.saveData.appPriceTypeList[index].maxmum;
      if (!result) {
        callback(new Error("必须为大于0的数字"));
      }else if(value > 9999){
        callback(new Error("最小数量限制4位数"));
      }else if(value > maxmum){
        callback(new Error("最小数量不能大于最大数量"));
      }else {
        callback();
      }

    };
    //校验倍数
    const validateMultiple = (rule,value,callback,a)=>{
      let reg = new RegExp(
        "^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$"
      );
      let result = reg.test(value);
      let index;
      for(let key in a){
        index = key;
      }
      index = index.split('.')[1];
      let maxmum = this.saveData.appPriceTypeList[index].maxmum;
      if (!result) {
        callback(new Error("必须为大于0的数字"));
      }else if(value > 99999){
        callback(new Error("倍数限制5位数"));
      }else if(maxmum % value !== 0){
        callback(new Error("最大数量必须整除数量倍数"));
      }else {
        callback();
      }

    };
    //1元兑换比例填数字类型可以为空的校验，同时把下面的规则改为 required:false ,去掉message 和type：number的校验
    const validateRatio = (rule, value, callback) => {
      if (value !== "" && value != null){
        const reg =/^[0-9]+$/;
        let result = reg.test(value);
        if (!result) {
          callback(new Error("只能输入大于0的正整数"));
        } else if(value === 0){
          callback(new Error("只能输入大于0的正整数"));
        }else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      // 列表传入的ID参数
      queryId: "",
      // 上传图片用到的文件参数
      file: "",
      checkNameError: "",
      baseUrl: this.$baseUrl,
      ftpUrl: this.$ftpUrl,
      baseUploadImg: 'this.src="' + this.$baseUploadImg + '"',
      /** 下拉框部分 **/
      searchFilter: {
        typeIdArr: [],
        cateIdArr: [],
        acpIdArr: [],
        acctIdArr: [],
        gameIdArr: []
      },

      savePriceData: {
        sort: 0,
        name: "",
        unit: "",
        multiple: "",
        minmum: "",
        maxmum: "",
        subscriptionRatio: ""
      },

      saveData: {
        // 商品基础信息
        appInfo: {
          id: this.queryId,
          code: "",
          cateId: "",
          acctId: "",
          acpId: "",
          gameId: "",
          typeId: "",
          name: "",
          icon: "",
          label: "",
          firstLetter: "",
          spllLetter: "",
          rechargeMode: 0,
          status: 0,
          sort: "",
          describe: "",
          pagePath: "",
          remark: "",
          isHot: "",
          isReco: 0
        },
        // 充值类型
        appPriceTypeList: [],
        // 商品详情 富文本
        appPage: {
          aiId: "",
          content: ""
        },

        // 上传的商品图标信息
        fileInfoList: []
      },
      fileList:[],//商品详情列表
      saveRule: {
        // 商品基础信息
        appInfo: {
          name: [
            { required: true, message: "请输入商品名称", trigger: "change" },
            {
              min: 1,
              max: 20,
              message: "长度在 1 到 20 个字符",
              trigger: "change"
            },
            {
              pattern: /^[\u4E00-\u9FA5A-Za-z0-9：《》]+$/,
              message: "不能用特殊符号",
              trigger: "change"
            }
          ],
          typeId: [
            { required: true, message: "请选择产品类型", trigger: "change" }
          ],
          cateId: [
            { required: true, message: "请选择商品品类", trigger: "change" }
          ],
          acctId: [
            { required: true, message: "请选择账号类型", trigger: "change" }
          ],
          acpId: [{ required: true, message: "请选择厂商", trigger: "change" }],
          rechargeMode: [
            { required: true, message: "请选到账方式", trigger: "change" }
          ],
          // isReco: [
          //   { required: true, message: "请选是否推荐", trigger: "change" }
          // ],
          icon: [
            {
              required: true,
              message: "请上传图片",
              trigger: "blur",
            },
            {validator: validateImage}
          ]
        }
      },
      saveRule2: {
        name: [
          { required: true, message: "请填写充值类型", trigger: "blur" },
          {
            validator: validateUnit
          }
        ],
        unit: [
          { required: true, message: "请填写充值单位", trigger: "blur" },
          {
            validator: validateUnit
          }
        ],
        maxmum: [
          { required: true, message: "请填写最大充值数量", trigger: "blur" },
          {
            validator: validateMaxnum
          }
        ],
        minmum: [
          { required: true, message: "请填写最小充值数量", trigger: "blur" },
          {
            validator: validateMinnum
          }
        ],
        subscriptionRatio: [
          // {
          //   required: true,
          //   message: "请填写1元兑换比例",
          //   trigger: "blur",
          // },
          {
            validator: validateRatio
          }
        ],
        multiple: [
          { required: true, message: "请填写输入数量的倍数", trigger: "blur" },
          {
            validator: validateMultiple
          }
        ]
      }
    };
  },
  created() {
    this.queryId = this.$route.query.id || "";
    this.getData();
    this.getSelectArr();
  },
  mounted() {
  },
  computed: {},
  methods: {
    // 获取数据
    getData() {
      if (this.queryId === "") {
        this.saveData.appPriceTypeList.push(
          JSON.parse(JSON.stringify(this.savePriceData))
        );
        return;
      }

      let searchData = { id: this.queryId };
      this.$postFetch(this.$api.ProInfo, searchData)
        .then(response => {
          let res = response.data;
          if (res.code !== 1) {
            console.log(res);
            this.$message.error(res.msg);
            return;
          }
          this.saveData = res.data;
          // 初始化商品充值类型
          if (this.saveData.appPriceTypeList.length === 0) {
            this.saveData.appPriceTypeList.push(
              JSON.parse(JSON.stringify(this.savePriceData))
            );
          } else {
            //添加充值类型
            let maxint = 0;
            this.saveData.appPriceTypeList.some((item, index) => {
              if (item.sort === undefined) {
                this.$set(item, "sort", maxint + 1);
              } else if (item.sort > maxint) {
                maxint = item.sort;
              }
            });
          }
          //处理商品详情数据
          this.saveData.fileInfoList.forEach(item =>{
            if (item.type === 6) {
              this.fileList.push({
                name:item.fileOrignName,
                url:this.ftpUrl+item.fileUrl
              })
            }
          });
          // 初始化富文本
          if (!this.saveData.appPage) {
            this.saveData.appPage = { content: "" };
          }
          // console.log(this.saveData);
          this.acpChange();
        })
        .catch(err => {
          console.log(err);
        });
    },

    save(val) {
      this.$refs["saveData"].validate(valid => {
        if (!valid || this.checkNameError) return;
        // console.log(this.saveData);
        console.log(JSON.stringify(this.saveData));
        if (this.saveData.appInfo.rechargeMode == 1) {
          this.saveData.appInfo.acctId = "";
          this.saveData.appInfo.gameId = "";
        }
        this.$postFetch(this.$api.ProSave, this.saveData)
          .then(response => {
            console.log(response);
            let res = response.data;
            if (res.code !== 1) {
              this.$message.error(res.msg);
              return;
            }
            this.$message.success("成功");
            if (val == 1) {
              // 保存并继续。执行新增/修改当前这条数据
              this.saveData = {
                // 商品基础信息
                appInfo: {
                  id: this.queryId,
                  code: "",
                  cateId: "",
                  acctId: "",
                  acpId: "",
                  gameId: "",
                  typeId: "",
                  name: "",
                  icon: "",
                  label: "",
                  firstLetter: "",
                  spllLetter: "",
                  rechargeMode: 0,
                  status: 0,
                  sort: "",
                  describe: "",
                  pagePath: "",
                  remark: "",
                  isHot: "",
                  isReco: 0
                },
                // 充值类型
                appPriceTypeList: [],
                // 商品详情 富文本
                appPage: {
                  aiId: "",
                  content: ""
                },
                // 上传的商品图标信息
                fileInfoList: []
              };
              this.fileList = [];
              // this.getData();
              // this.getSelectArr();
              this.$refs.saveData.resetFields();
              this.$router.push({ path: "/product/detail", query: { id: "" } });
            } else {
              this.$router.push({ path: "/product/list" });
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // 获取添加商品中select的数据
    getSelectArr() {
      // 帐号类型(列表不用)
      this.$postFetch(this.$api.actList)
        .then(response => {
          if (response.data.code !== 1) {
            this.$message.error(response.data.msg);
            return;
          }
          this.searchFilter.acctIdArr = response.data.data;
        })
        .catch(err => {
          console.log(err);
        });

      // // 区服配置(列表不用)
      // let getParams = {p_id: this.saveData.appInfo.acpId, type: 0};
      // this.$getFetch(this.$api.game_list, getParams).then(response => {
      //   if (response.data.code !== 1) {
      //     this.$message.error(response.data.msg);
      //     return;
      //   }
      //   this.searchFilter.gameIdArr = response.data.data;
      // }).catch(err => {
      //   console.log(err);
      // });

      // 分类
      this.$postFetch(this.$api.appcateList)
        .then(response => {
          if (response.data.code !== 1) {
            this.$message.error(response.data.msg);
            return;
          }
          this.searchFilter.cateIdArr = response.data.data;
        })
        .catch(err => {
          console.log(err);
        });

      // 类别
      this.$postFetch(this.$api.apptypeList)
        .then(response => {
          if (response.data.code !== 1) {
            this.$message.error(response.data.msg);
            return;
          }
          this.searchFilter.typeIdArr = response.data.data;
        })
        .catch(err => {
          console.log(err);
        });

      // 厂商
      this.$postFetch(this.$api.companyList)
        .then(response => {
          if (response.data.code !== 1) {
            this.$message.error(response.data.msg);
            return;
          }
          this.searchFilter.acpIdArr = response.data.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    //厂商改变时

    acpChange(val) {
      if(val){
        //产商改变
        this.saveData.appInfo.gameId = "";
      }
      this.searchFilter.gameIdArr = [];
      let getParams = { pid: this.saveData.appInfo.acpId, type: 1 };
      // 区服配置(列表不用)
      this.$postFetch(this.$api.gameList, getParams)
        .then(response => {
          if (response.data.code !== 1) {
            this.$message.error(response.data.msg);
            return;
          }
          this.searchFilter.gameIdArr = response.data.data;
          if (this.searchFilter.gameIdArr.length === 0) {
            this.saveData.appInfo.gameId = "";
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    preview() {
      console.log("预览");
    },
    closeForm() {
      this.$router.push({ path: "/product/list" });
    },

    addDomain() {
      //添加充值类型
      let priceData = JSON.parse(JSON.stringify(this.savePriceData));
      let maxint = 0;

      if (this.saveData.appPriceTypeList.length >= 5) {
        this.$message.error("至少一个，至多五个");
        return false;
      }

      this.saveData.appPriceTypeList.some((item, index) => {
        if (item.sort > maxint) {
          maxint = item.sort;
        }
      });

      priceData.sort = maxint + 1;
      // console.log(priceData);
      this.saveData.appPriceTypeList.push(priceData);
    },
    delDomain(item,index) {
      this.saveData.appPriceTypeList.splice(index,1)
      //删除充值类型
      /*this.saveData.appPriceTypeList.some((priceData, index) => {
        if (priceData.sort === sort) {
          console.log(priceData.sort);
          this.saveData.appPriceTypeList.splice(index, 1);
          return true;
        }
      });*/
    },

    //文件改变时
    changeUpload(file) {
      let windowURL = window.URL || window.webkitURL;
      this.saveData.appInfo.icon = windowURL.createObjectURL(file.raw);
    },
    //文件上传前
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 < 200;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG、PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 200k!");
        return false;
      }
      this.file = file;
      let param = new FormData(); //创建form对象
      param.append("file", this.file, this.file.name);
      param.append("directoryType", 1);
      this.$postFetch(this.$api.uploadFile, param, "upload")
        .then(response => {
          let res = response.data;
          if (res.code !== 1) {
            this.$message.error(res.msg);
            return false;
          }
          this.$message.success("上传成功!");

          // contextType: "image/png"
          // fileOrignName: "512_512.png"
          // fileUrl: "3b8cd2daeded4644bdfa66bbc4b3652d.png"

          // this.saveData.fileInfoList = res.data;
          // this.saveData.fileInfoList.type = 1;
          // this.saveData.appInfo.icon = res.data.fileUrl;
          // this.$refs["saveData"].validateField("appInfo.icon");

          let data = res.data;
          data.type = 1;

          let isHave = false;
          if (this.saveData.fileInfoList.length > 0) {
            this.saveData.fileInfoList.forEach(item => {
              if (item.type == 1) {
                isHave = true;
                item = data;
              }
            });
          }

          if (!isHave) {
            this.saveData.fileInfoList.push(data);
          }

          this.saveData.appInfo.icon = res.data.fileUrl;
          // this.$refs.saveData.validateField("appInfo.icon");
          this.$refs["saveData"].validateField("appInfo.icon");
        })
        .catch(err => {
          console.log(err);
        });
      return false;
    },
    //文件删除时
    handleRemove(file,fileList) {
      // console.log(file);
      // console.log(fileList);
      // console.log(this.saveData.fileInfoList)
      this.saveData.fileInfoList.forEach((item,index) =>{
        if(file.url.indexOf(item.fileUrl) > -1){
            this.saveData.fileInfoList.splice(index,1);
            this.fileList = fileList;
        }
      })
      console.log(this.saveData.fileInfoList)
    },
    //文件改变时
    changeUploadContent(file) {
      console.log(file);
      // let windowURL = window.URL || window.webkitURL;
      // this.saveData.appInfo.icon = windowURL.createObjectURL(file.raw);
    },
    //文件上传前
    beforeUploadContent(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 < 200;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG、PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 200k!");
        return false;
      }

      this.file = file;
      let param = new FormData(); //创建form对象
      param.append("file", this.file, this.file.name);
      param.append("directoryType", 6);
      this.$postFetch(this.$api.uploadFile, param, "upload")
        .then(response => {
          let res = response.data;
          if (res.code !== 1) {
            this.$message.error(res.msg);
            return false;
          }
          this.$message.success("上传成功!");

          // contextType: "image/png"
          // fileOrignName: "512_512.png"
          // fileUrl: "3b8cd2daeded4644bdfa66bbc4b3652d.png"

          let data = res.data;
          data.type = 6;

          this.saveData.fileInfoList.push(data);
          //处理商品详情数据
          this.fileList.push({
            name:data.fileOrignName,
            url:this.ftpUrl+data.fileUrl
          });
          //不需要下面的代码，添加商品详情上传的图片不需要给url也不做校验
          // this.saveData.appInfo.icon = res.data.fileUrl;
          // this.$refs["saveData"].validateField("appInfo.icon");
          // this.$refs.saveData.validateField("appInfo.icon");
        })
        .catch(err => {
          console.log(err);
        });
      return false;
    },

    checkName() {
      console.log("checkName");
      //检验名称重复
      this.checkNameError = "";
      let params = { name: this.saveData.appInfo.name };
      this.$getFetch(this.$api.checkProName, params)
        .then(res => {
          let data = res.data;
          if (data.code !== 1) {
            this.$message.error(data.msg);
            return;
          }

          if (data.data) {
            this.checkNameError = "商户名称已存在";
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    isContains(str, substr) {
      if (str) {
        return str.indexOf(substr) >= 0;
      }
      return false;
    }
  }
};
</script>
<style lang="less" type="text/less">
.saveData_recharge_type.border-bottom {
  border-bottom: #3f444e solid 1px;
}

.saveData_recharge_type {
  .el-form-item__label {
    text-align: center !important;
  }

  i {
    line-height: 40px;
    color: #7d72e4;
    font-size: 25px;
    padding-left: 10px;
  }

  .el-col-3 + .el-col-3 {
    margin-left: 6px;
  }
}

.saveData_recharge_type + .saveData_recharge_type {
  margin-top: 20px;
}

.upload-img {
  width: 40px;
  height: 35px;
  vertical-align: middle;
  float: left;
}

.add-moc-upload {
  /*width: 40%;*/
  float: left;

  .el-upload {
    /*width: 70%;*/
    margin-left: 20px;

    .el-upload-dragger {
      width: 100%;
      height: 35px;
    }
  }
}
.upload-content-img {
  width: 50%;
  height: auto;
  /*width: auto;*/
  /*height: 100px;*/
  vertical-align: middle;
  float: left;
}

.uploadBox .add-content-upload {
  width: 100%;
  float: left;

  .el-upload {
    width: 230px;
    .el-upload-dragger {
      width: 100%;
      height: 35px;
    }
  }
  .el-upload-list--picture .el-upload-list__item{
    float: left;
    margin-right: 10px;
    width: 230px;
  }
}

.el-input.is-disabled .el-input__inner {
  color: #223252 !important;
}

.formRequired {
  .el-form-item.is-required:not(.is-no-asterisk) {
    .el-form-item__label:before {
      content: "*";
      color: #f56c6c;
      margin-left: 20%;
      // float: left;
    }
  }
}
</style>
